<script setup>
import { getTeahProjList } from '@/api/teacher/teacher.js'
import { useUserStore } from '@/stores'
import { NButton,useMessage } from 'naive-ui'
import { downloadFile,getApprovalResult,addApprovalRecord,addApprovalRecords } from '@/api/secretary/secretary.js'
import { baseURL } from "@/utils/request.js"

const message = useMessage()
/* 审核消息通知 */
//通过 defineEmits编译器宏生成emit方法
const emit = defineEmits(['get-check-num'])
const sendNum = () => {
  //触发自定义时间 并传递参数
  // console.log("子组件自定义事件触发了",itemCount.value)
  emit('get-check-num','teachingProject')
}



/* 获取审核结果列表 */
const resultOpinion = ref()
const getResult = async() => {
  const { data: res } = await getApprovalResult()
  if(res.code === 1) {
    resultOpinion.value = res.data.map(item => ({label:item.result,value:item.id}))
  }
  else if( res.code === 0) {
    message.error(res.msg)
  }
}
//调用获取审核结果列表方法
getResult()


/* 表格信息 */
const columns = [
  { type: 'selection',
    disabled(row) {
      if(userStore.roleId === 2) {
        return row.status !== '待初审'
      } else if(userStore.roleId === 3) {
        return row.status !== '待复核'
      }
    }},
  { title: '序号', key: 'key', render: (_,index) =>`${index + 1}`, align: "center" },
  { title: '申请人',key: 'name', align: 'center' },
  { title: '工号',key: 'jobNumber', align: 'center' },
  { title: '项目名称', key: 'projectName', align: "center" },
  { title: '项目级别', key: 'level', align: "center" },
  { title: '获批年度', key: 'year', align: "center" },
  { title: '项目负责人', key: 'leader', align: "center" },
  { title: '其他成员', key: 'others', align: "center" },
  { title: '相关附件', key: 'attachment', align: "center", render: row => {
      if(row.attachment !== null) {
        let attachmentArray = row.attachment.split(',')
        const displayArray = ref([])
        attachmentArray.forEach((item,index) => {
          displayArray.value.push (h(NButton,{
                size: 'small', type:'info', quaternary: true, onClick: () => {
                  const url = baseURL + item
                  window.open(url,"_blank")
                }
              },
              {default: () => '附件'+ `${index + 1}`}
          ))
        })
        return displayArray.value
      }
    }},
  { title: '备注', key: 'comment', align: "center" },
  { title: '审核状态', key: 'status', align: "center"},
  { title: '操作', key: 'operate', align: "center", render: row => {
      if(userStore.roleId === 2){
        if(row.statusId=== 2) {
          return [
            h(NButton, {
                  size: 'small', type: 'primary', secondary: true, onclick: () => {
                    showMoreModal.value = true
                    viewForm.value.name = row.name
                    viewForm.value.jobNumber = row.jobNumber
                    viewForm.value.projectName = row.projectName
                    viewForm.value.level = row.level
                    viewForm.value.year = row.year
                    viewForm.value.leader = row.leader
                    viewForm.value.others = row.others
                    viewForm.value.otherJobNumber = row.otherJobNumber;
                    othersData.value = [];
                    let nameArray = []
                    let jobNumberArray = []
                    if (row.others !== null) nameArray = viewForm.value.others.split('，');
                    if (row.otherJobNumber !== null) jobNumberArray = viewForm.value.otherJobNumber.split(',');
                    nameArray.forEach((item, index) => {
                      if (jobNumberArray[index] === 'null') {
                        othersData.value.push({type: '院外', name: item, jobNumber: null})
                      } else {
                        othersData.value.push({type: '院内', name: item, jobNumber: jobNumberArray[index]})
                      }
                    })
                    viewForm.value.attachment = row.attachment
                    pathArray.value = []
                    if (row.attachment !== null) pathArray.value = row.attachment.split(',')
                    viewForm.value.comment = row.comment
                  }
                },
                {default: () => '详情'}
            ),
            h(NButton, {
                  size: 'small', type: 'info', secondary: true, onclick: () => {
                    checkValue.value.approvalPhaseId = 1
                    checkValue.value.approvalResultId = 1
                    checkValue.value.achievementId = row.codeNumber
                    checkValue.value.opinion = null
                    showCheckModal.value = true
                  }
                },
                {default: () => '审核'}
            )
          ]
        }
        else if(row.statusId===3||row.statusId===4||row.statusId===5||row.statusId===6){
          return [
            h(NButton, {
                  size: 'small', type: 'primary', secondary: true, onclick: () => {
                    showMoreModal.value = true
                    viewForm.value.name = row.name
                    viewForm.value.jobNumber = row.jobNumber
                    viewForm.value.projectName = row.projectName
                    viewForm.value.level = row.level
                    viewForm.value.year = row.year
                    viewForm.value.leader = row.leader
                    viewForm.value.others = row.others
                    viewForm.value.otherJobNumber = row.otherJobNumber;
                    othersData.value = [];
                    let nameArray = []
                    let jobNumberArray = []
                    if (row.others !== null) nameArray = viewForm.value.others.split('，');
                    if (row.otherJobNumber !== null) jobNumberArray = viewForm.value.otherJobNumber.split(',');
                    nameArray.forEach((item, index) => {
                      if (jobNumberArray[index] === 'null') {
                        othersData.value.push({type: '院外', name: item, jobNumber: null})
                      } else {
                        othersData.value.push({type: '院内', name: item, jobNumber: jobNumberArray[index]})
                      }
                    })
                    viewForm.value.attachment = row.attachment
                    pathArray.value = []
                    if (row.attachment !== null) pathArray.value = row.attachment.split(',')
                    viewForm.value.comment = row.comment
                  }
                },
                {default: () => '详情'}
            )
          ]
        }
      }else if(userStore.roleId === 3){
        if(row.statusId===3){
          return [
            h(NButton, {
                  size: 'small', type: 'primary', secondary: true, onclick: () => {
                    showMoreModal.value = true
                    viewForm.value.name = row.name
                    viewForm.value.jobNumber = row.jobNumber
                    viewForm.value.projectName = row.projectName
                    viewForm.value.level = row.level
                    viewForm.value.year = row.year
                    viewForm.value.leader = row.leader
                    viewForm.value.others = row.others
                    viewForm.value.otherJobNumber = row.otherJobNumber;
                    othersData.value = [];
                    let nameArray = []
                    let jobNumberArray = []
                    if (row.others !== null) nameArray = viewForm.value.others.split('，');
                    if (row.otherJobNumber !== null) jobNumberArray = viewForm.value.otherJobNumber.split(',');
                    nameArray.forEach((item, index) => {
                      if (jobNumberArray[index] === 'null') {
                        othersData.value.push({type: '院外', name: item, jobNumber: null})
                      } else {
                        othersData.value.push({type: '院内', name: item, jobNumber: jobNumberArray[index]})
                      }
                    })
                    viewForm.value.attachment = row.attachment
                    pathArray.value = []
                    if (row.attachment !== null) pathArray.value = row.attachment.split(',')
                    viewForm.value.comment = row.comment
                  }
                },
                {default: () => '详情'}
            ),
            h(NButton, {
                  size: 'small', type: 'info', secondary: true, onclick: () => {
                    checkValue.value.approvalPhaseId = 2
                    checkValue.value.approvalResultId = 1
                    checkValue.value.achievementId = row.codeNumber
                    checkValue.value.opinion = null
                    showCheckModal.value = true
                  }
                },
                {default: () => '审核'}
            )
          ]
        } else if(row.statusId===4||row.statusId===5||row.statusId===6){
          return [
            h(NButton, {
                  size: 'small', type: 'primary', secondary: true, onclick: () => {
                    showMoreModal.value = true
                    viewForm.value.name = row.name
                    viewForm.value.jobNumber = row.jobNumber
                    viewForm.value.projectName = row.projectName
                    viewForm.value.level = row.level
                    viewForm.value.year = row.year
                    viewForm.value.leader = row.leader
                    viewForm.value.others = row.others
                    viewForm.value.otherJobNumber = row.otherJobNumber;
                    othersData.value = [];
                    let nameArray = []
                    let jobNumberArray = []
                    if (row.others !== null) nameArray = viewForm.value.others.split('，');
                    if (row.otherJobNumber !== null) jobNumberArray = viewForm.value.otherJobNumber.split(',');
                    nameArray.forEach((item, index) => {
                      if (jobNumberArray[index] === 'null') {
                        othersData.value.push({type: '院外', name: item, jobNumber: null})
                      } else {
                        othersData.value.push({type: '院内', name: item, jobNumber: jobNumberArray[index]})
                      }
                    })
                    viewForm.value.attachment = row.attachment
                    pathArray.value = []
                    if (row.attachment !== null) pathArray.value = row.attachment.split(',')
                    viewForm.value.comment = row.comment
                  }
                },
                {default: () => '详情'}
            )
          ]
        }
      }
    } }
]

/* 批量审核 */
//批量审核按钮的显示与禁用
const checkStatus = ref(true)
const checkedRowKeysRef = ref([]);
const handleCheck = (rowkeys) => {
  if(rowkeys.length === 0) {
    checkStatus.value=true
    checkedRowKeysRef.value = []
  }
  else checkStatus.value=false
  checkedRowKeysRef.value = rowkeys;
  console.log(checkedRowKeysRef.value);
}
const rowKey = (row) => row.codeNumber

const showCheckModal2 = ref(false)
const batchCheck = () => {
  showCheckModal2.value = true
  checkValue.value.achievementId = checkedRowKeysRef.value.toString()
  if(userStore.roleId === 2) checkValue.value.approvalPhaseId = 1
  else if(userStore.roleId === 3) checkValue.value.approvalPhaseId = 2
}

//批量审核结果确认方法
const onPositiveClick2 = async() => {
  const { data: res } = await addApprovalRecords(checkValue.value)
  if(res.code === 1) {
    message.success('审核成功')
    showCheckModal2.value = false
    await onUpdatePage()
    for(let i = 0; i < checkedRowKeysRef.value.length; i++) { sendNum() }
    checkedRowKeysRef.value = []
    checkStatus.value=true

  }
  else if(res.code === 0) message.error(res.msg)
}
//审核结果取消方法
const onNegativeClick2 = () => {
  showCheckModal2.value = false
}


/* 分页 */
const currentPage = ref(1)
const page_size = ref(10)
const itemCount = ref(null)
const onUpdatePage = async() => {
  if(userStore.roleId === 2){
    formValue.value.statusId= 2
  }else if(userStore.roleId === 3){
    formValue.value.statusId= 3
  }
  if (time.value != null) {
    const startTime = formatTime(time.value[0])
    const endTime = formatTime(time.value[1])
    formValue.value.startTime = startTime
    formValue.value.endTime = endTime
  } else {
    formValue.value.startTime = null
    formValue.value.endTime = null
  }
  formValue.value.pageSize = page_size.value
  formValue.value.page = currentPage.value
  const { data:res } = await getTeahProjList(formValue.value)
  if (res.code  === 1) {
    data.value = res.data.rows
    itemCount.value = res.data.total
  }
  else if(res.code === 0) {
    message.error(res.msg)
  }
}

/* 获取要审核的教学项目列表 */
const data = ref([])
const userStore = useUserStore()
const getData = async() => {
  const statusId = userStore.roleId
  const roleId = userStore.roleId
  const pageSize = page_size.value
  const { data:res } = await getTeahProjList({roleId,statusId,pageSize})
  if (res.code  === 1) {
    data.value = res.data.rows
    itemCount.value = res.data.total
  }
  else if(res.code === 0) {
    message.error(res.msg)
  }
}
//调用获取需要审核的教师教学项目列表
getData()

/* 详情模态框 */
const showMoreModal = ref(false)
const viewForm = ref({
  name: null,
  jobNumber: null,
  projectName: null,
  level: null,
  year: null,
  leader: null,
  others: null,
  otherJobNumber: null,
  attachment: null,
  comment: null,
})
const othersColumns = [
  {title:'排名',key:'key',render:(_,index)=>`${index + 1}`,align:"center" },
  {title:'类别',key:'type',align:"center"},
  {title:'姓名',key:'name',align:"center"},
  {title:'工号',key:'jobNumber',align:"center"}
]
const othersData = ref([])
const pathArray = ref([])


/* 审核模态框 */
const showCheckModal = ref(false)
const checkValue=ref({
  approvalPhaseId: null,
  approvalResultId: 1,
  achievementId: null,
  achievementTypeId: 1,
  opinion: null
})
//审核结果确认方法
const onPositiveClick = async() => {
  const { data: res } = await addApprovalRecord(checkValue.value)
  if(res.code === 1) {
    message.success('审核成功')
    showCheckModal.value = false
    await onUpdatePage()
    sendNum()
  }
  else if(res.code === 0) message.error(res.msg)
}
//审核结果取消方法
const onNegativeClick = () => {
  showCheckModal.value = false
}


//快捷键查询
const selectButtonClicked = () => searchAchievement();

// 添加键盘按下事件监听器
onMounted(() => {
  const handleKeyDown = (event) => {
    if (event.key === "Enter") {
      selectButtonClicked();
    }
  };

  // 注册监听器
  window.addEventListener('keydown', handleKeyDown);

  // 在组件卸载时移除监听器以防止内存泄漏
  onUnmounted(() => {
    window.removeEventListener('keydown', handleKeyDown);
  });
});

/* 条件查询成果信息 */
const time = ref(null)
const formValue = ref({
  statusId: null,
  achievementTypeId: 1,
  name: null,
  jobNumber: null,
  projectName: null,
  roleId: userStore.roleId,
  startTime: null,
  endTime: null,
  pageSize: null,
  page: null
})

/* 查询功能 */
const searchAchievement = async() => {
  if (time.value != null) {
    const startTime = formatTime(time.value[0])
    const endTime = formatTime(time.value[1])
    formValue.value.startTime = startTime
    formValue.value.endTime = endTime
  } else {
    formValue.value.startTime = null
    formValue.value.endTime = null
  }
  if(userStore.roleId === 2){
    formValue.value.statusId= 2
  }else if(userStore.roleId === 3){
    formValue.value.statusId= 3
  }
  const {data: res} = await getTeahProjList(formValue.value)
  if (res.code === 1) {
    data.value = res.data.rows
    itemCount.value = res.data.total
    currentPage.value = 1
  } else if (res.code === 0) {
    message.error(res.msg)
  }
}

/* 将时间戳格式化为年-月-日 */
const formatTime = (time) => {
  const date = new Date(time)
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0') // 获取月份并补零
  const day = date.getDate().toString().padStart(2, '0') // 获取日期并补零
  const formattedDate = `${year}-${month}-${day}`
  return formattedDate
}

</script>

<template>
  <div>
    <div class="title">教学项目信息审核</div>
    <div class="function">
      <n-space style="margin-bottom: 5px;">
        <n-form
            inline
            label-placement="left"
            :model="formValue"
            size="small"
        >
          <n-form-item label="时间" path="time">
            <n-date-picker v-model:value="time" type="monthrange" clearable style="width: 200px" />
          </n-form-item>
          <n-form-item label="姓名" path="name">
            <n-input v-model:value="formValue.name" placeholder="输入姓名" style="width: 100px;" />
          </n-form-item>
          <n-form-item label="工号" path="jobNumber">
            <n-input v-model:value="formValue.jobNumber" placeholder="输入工号" />
          </n-form-item>
          <n-form-item label="项目名称" path="projectName">
            <n-input v-model:value="formValue.projectName" placeholder="输入项目名称" />
          </n-form-item>
          <n-form-item>
            <n-button attr-type="button" @click="searchAchievement" type="info">
              查询
            </n-button>
          </n-form-item>
        </n-form>
      </n-space>
      <n-space style="margin-bottom: 5px;">
        <n-button attr-type="button" :disabled="checkStatus" @click="batchCheck" type="info">
          批量审核
        </n-button>
      </n-space>
    </div>
    <n-data-table
        :columns="columns"
        :data="data"
        bordered
        :single-line="false"
        :row-key="rowKey"
        v-model:checked-row-keys="checkedRowKeysRef"
        @update:checked-row-keys="handleCheck"

    />
    <div class="pagination">
      <n-pagination v-model:page="currentPage"
                    @update-page="onUpdatePage"
                    :page-size="page_size"
                    :item-count="itemCount"/>
    </div>
    <!-- 详情模态框 -->
    <n-modal v-model:show="showMoreModal">
      <n-card style="width: 650px;"
              title="教学项目详情"
              bordered
              closable
              @close="showMoreModal=false"
              size="small"
              role="dialog"
              aria-modal="true">
        <n-form style="padding-top: 10px;"
                label-placement="left"
                label-width="100"
                label-align="right">
          <n-form-item label="申请人:" path="name">
            <span>{{ viewForm.name }}</span>
          </n-form-item>
          <n-form-item label="工号:" path="jobNumber">
            <span>{{ viewForm.jobNumber }}</span>
          </n-form-item>
          <n-form-item label="项目名称:" path="projectName">
            <span>{{ viewForm.projectName }}</span>
          </n-form-item>
          <n-form-item label="项目级别:" path="level">
            <span>{{ viewForm.level }}</span>
          </n-form-item>
          <n-form-item label="获批年度:" path="year">
            <span>{{ viewForm.year }}</span>
          </n-form-item>
          <n-form-item label="项目负责人:" path="leader">
            <span>{{ viewForm.leader }}</span>
          </n-form-item>
          <n-form-item label="其他成员:" path="others">
            <n-data-table
                bordered
                :columns="othersColumns"
                :single-line="false"
                :data="othersData"
                size="small"
            />
          </n-form-item>
          <n-form-item label="相关附件:" path="attachment">
            <a style="margin-right: 5px; color: #2080f0;" v-for="(item,index) in pathArray" :key="index" :href = "baseURL+ item" target="_blank">附件{{ index + 1 }}</a>
          </n-form-item>
          <n-form-item label="备注:" path="comment">
            <span>{{ viewForm.comment }}</span>
          </n-form-item>
        </n-form>
      </n-card>
    </n-modal>

    <!-- 审核模态框 -->
    <n-modal
        v-model:show="showCheckModal"
        :mask-closable="false"
        preset="dialog"
        title="审核"
        positive-text="确认"
        negative-text="取消"
        @positive-click="onPositiveClick"
        @negative-click="onNegativeClick"
    >
      <div>
        <n-space vertical>
          <n-select v-model:value="checkValue.approvalResultId" :options="resultOpinion" placeholder="审核意见" />
          <n-input
              v-model:value="checkValue.opinion"
              type="textarea"
              placeholder="审核意见"
          />
        </n-space>
      </div>
    </n-modal>

    <!-- 批量审核模态框 -->
    <n-modal
        v-model:show="showCheckModal2"
        :mask-closable="false"
        preset="dialog"
        title="审核"
        positive-text="确认"
        negative-text="取消"
        @positive-click="onPositiveClick2"
        @negative-click="onNegativeClick2"
    >
      <div>
        <n-space vertical>
          <n-select v-model:value="checkValue.approvalResultId" :options="resultOpinion" placeholder="审核意见" />
          <n-input
              v-model:value="checkValue.opinion"
              type="textarea"
              placeholder="审核意见"
          />
        </n-space>
      </div>
    </n-modal>
  </div>
</template>

<style scoped>
.pagination {
  float: right;
  padding-top: 20px;
  padding-bottom: 20px;
}
.title{
  color: rgb(5,93,163);
  text-align: center;
  font-size:22px;
  font-family: "Microsoft Yahei","Helvetica Neue", Helvetica, Arial, sans-serif;
  border-bottom: 1px solid rgb(193, 217, 237);
  margin-bottom: 5px;
}
::v-deep .n-data-table-th__title{
  font-weight: 600;
}
span {
  width: 100%;
  padding: 5px;
  border: 1px solid rgb(184, 182, 182);
  min-height: 15px;
}
::v-deep .n-data-table-td{
  padding: 6px;
}
.function{
  display: flex;
  justify-content: space-between;
}
</style>
